import threading,time,random
def light():
    while True:
        while True:
            if event.isSet():
                event.clear()  # 将值改成False
                print("\033[1;31;m红灯亮了\033[0m")
                time.sleep(5)  # 红灯停3秒
            else:
                event.set()  # 将值改成True
                print("\033[1;32;m绿灯亮了\033[0m")
                time.sleep(10)
def car(name):
    if event.isSet():  # 绿灯,不阻塞
        print("%s 行驶通过..."%name)
    else:  # 程序阻塞,红灯
        print("%s 正在等待红灯结束...."%name)
        event.wait()
        print("红灯结束,%s 继续行驶...." % name)
if __name__ == "__main__":
    event = threading.Event()
    light = threading.Thread(target=light)  # 创建一个红绿灯
    light.start()
    for i in range(100):  # 不断有车在马路上形式
        # 注意:线程名不能与函数名重复
        c = threading.Thread(target=car, args=("第%s辆车"%str(i+1),))
        c.start()
        time.sleep(random.randrange(1, 5))  # 陆续有车形式  1~5随机秒
